<template>
  <div class="bg">
    <div class="container">
      <div style="font-size: 20px; font-weight: bold;text-align: center ;color: rgb(95, 100, 102);line-height: 80px;">修改密码</div>
      <div style="align-items: center;padding: 0 40px;">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules"
              label-width="auto" class="demo-ruleForm" >
          <el-form-item label="用户名" prop="user_name">
              <el-input v-model="ruleForm.user_name" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="密  码" prop="password">
              <el-input v-model="ruleForm.password"  type="password" placeholder="请输入密码"  show-password autocomplete="off" />
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
              <el-input  style="margin-top: 10px;" v-model="ruleForm.checkPass"  type="password" placeholder="请确认密码"  show-password autocomplete="off"/>
          </el-form-item>
          <el-form-item v-if="ruleForm.password !== '' && ruleForm.password !== undefined" label="" align="center" style="height: 25px;" >
        <!-- 展示长度条 -->
          <div class="bar" v-if="ruleForm.password !== '' && ruleForm.password !== undefined" :style="{ background: barColor, width: width + '%' }">
          <!-- 展示文字 -->
          <div class="strength" :style="{ color: barColor }" v-if="ruleForm.password !== '' && ruleForm.password !== undefined"> {{ strength }} </div>
          </div>
        </el-form-item>
      </el-form>
      <div style="margin-top: 30px; padding: 0 70px;" > 
        <div style="float: left;" ><el-button type="primary" @click="changePwd(ruleFormRef)">修 改</el-button></div>
        <div style="float: right;" ><el-button @click="reset(ruleFormRef)">重 置</el-button></div>
      </div>
      <div style="margin-top: 80px; padding: 0 30px;" >
          <div style="float: left;"><a style="color: #1a2ee6;text-decoration: none;" href="http://localhost:3000/register">新注册</a></div>
          <div style="float: right;"><a style="color: #1a2ee6;text-decoration: none;" href="http://localhost:3000/login">登录</a></div>
      </div>
    </div>
   </div>
  </div>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref,watch } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import{changePwdApi} from '../utils/api/login'
  //加密
  import {Encrypt} from '../utils/aes'
  // 引入验证方法
  import { level ,checkPasswordRule} from '../stores/CheckPassword'
  import {ElMessage,ElMessageBox}from 'element-plus'
  //路由
  import {useRouter} from 'vue-router'
  // 强度条颜色
  const barColor = ref('')
  // 强度条长度
  const width = ref('')
  // 强度条说明
  const strength = ref('')
  const ruleFormRef = ref<FormInstance>()
	const router = useRouter()
  const ruleForm = reactive({
    password: '',
    checkPass: '',
    user_name: '',
    id:''
  })

  const checkUserName = (rule: any, value: any, callback: any) => {
          if (value.trim() === '') {
              callback(new Error("用户名不可为空"))
          } else {
              return callback();
          }}
  
  const validatePass = (rule: any, value: string, callback: any) => {
    if (value.trim() === '') {
         callback(new Error("请输入密码"))
    } else {
      if (ruleForm.checkPass !== '') {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validateField('checkPass')
      }
      const result: string = checkPasswordRule(value,ruleForm.user_name);
      if (result === '校验通过') {
        callback();
      } else {
        callback(new Error(result));
      }
    }
  }

  const comValidatePass = (rule: any, value: any, callback: any) => {
    if (value.trim() === '') {
        callback(new Error("请再次确认密码"))
    } else if (value !== ruleForm.password) {
      callback(new Error("两次密码输入不匹配"))
    } else {
      callback()
    }
  }
  
  watch(() => ruleForm.password,
    (newVal) => {
      if (newVal != '') {
        const res: string = level(newVal);
        if (res == '非常弱') {
          barColor.value = 'red';
          width.value = '20';
          strength.value = '非常弱';
        } else if (res == '弱') {
          barColor.value = '#ee795c';
          width.value = '40';
          strength.value = '弱';
        } else if (res == '一般') {
          barColor.value = 'orange';
          width.value = '60';
          strength.value = '一般';
        } else if (res == '强') {
          barColor.value = 'green';
          width.value = '80';
          strength.value = '强';
        } else if (res == '非常强') {
          barColor.value = '#1B8EF8';
          width.value = '100';
          strength.value = '非常强';
        }
      }
    }
  )
  const rules = reactive<FormRules<typeof ruleForm>>({
    user_name: [{required: true, message: '请输入3-20位用户名', trigger: 'blur'},
              {
                  min: 3,
                  max: 20,
                  message: '请输入3-20位用户名',
                  trigger: 'blur'
              },
              {
                  validator: checkUserName,
                  trigger: 'blur'}
                ],
    password: [{required: true, message: '请输入8-16位密码', trigger: 'blur'},
              {
                  min: 8,
                  max: 16,
                  message: '请输入8-16位密码',
                  trigger: 'blur'
              },
              {
                  validator: validatePass,
                  trigger: 'blur'}],
    checkPass: [{ required: true,validator: comValidatePass, trigger: 'blur' }],
  })
  
  const changePwd = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        // 发送修改密码请求
        changePwdApi(
          {user_name: ruleForm.user_name, 
					password: ruleForm.password}
        ).then((res:{code:string;message:any})=> {
          if(res.code !="0"){
             ElMessage.error(res.message)
          }else{
            // 密码修改成功
            ElMessageBox.confirm('密码一旦修改成功将使用新密码进行登录，您是否要修改？','温馨提示',
           {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
           }
           ).then(() => {
            ElMessage({
              type: 'success',
              message: res.message,
            })
            router.push('/login')
          }).catch(() => {
            ElMessage({
              type: 'info',
              message: '取消修改',
            })
            router.push('/login')
          }) 
        }
					
				}).catch(error=>{
          ElMessage.error(error.response.data.message)
        })
      } else {
        ElMessage.error("请输入正确的格式")
      }
    })
  }
  
  const reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
 
  </script>
  
  <style scoped>
      .bg{
      margin: 0; 
      padding: 0; 
      width: 100%; 
      height: 100vh; 
      background-image:  url('../assets/img/BG.png'); 
      background-size: cover; 
      background-repeat: no-repeat; 
      background-position: center; 
      }
      .container {
          width: 400px;
          height: 390px;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          background-color: #fdffff;
          border-radius: 10px;

      }
      
      .strength {
        font-size: 13px;
        color: #271E25;
        position: relative;
        top: 5px;
        left: 0;
        transition: 0.5s all ease;
      }  
      .bar {
        /* width: 400px; */
        height: 5px;
        background: red;
        transition: 0.5s all ease;
        max-width: 420px;
        margin: 2px 0 5px 5px;
        position: absolute;

      }
  </style>